// ==UserScript==
// @name           Vkontakte Download Music
// @namespace      http://polkila.googlecode.com
// @author         Васютинский Олег
// @version        10.09
// @include        http://*vkontakte.ru*
// @exclude        http://*vkontakte.ru/*act=edit*
// @include        http://*vk.com*
// @exclude        http://*vk.com/*act=edit*
// ==/UserScript==

var scriptName = 'VkontakteRu.DownloadMusic';
var scriptVersion = 10.09;
var lang = parseInt(readCookie('remixlang'));

(function(){
	setStyle('.download{font-size:16px;line-height:9px;}');
	function parse(){
		var imgs = document.images;
		for (n in imgs){
			if (imgs[n].className!='playimg') continue;
			if (!/[0-9]/.test(parseInt(n))) continue; //opera
			if (imgs[n].getAttribute('data-down')=='1') continue;
			imgs[n].setAttribute('data-down', '1');
			var params = /http:\/\/([^']+)/.exec(imgs[n].parentNode.innerHTML);
			(imgs[n].parentNode.nextSibling.nextSibling || imgs[n].parentNode.nextSibling).firstChild.innerHTML+=' <a class="download" href="http://'+params[1]+'" target="_blank">&#8674;</a>';
		}
		setTimeout(parse, 2000);
	}
	parse();
    setTimeout(checkForUpdate, 2000);
})();

function setStyle(str){
	node = document.createElement('style');
	node.appendChild(document.createTextNode(str));
	getHead().appendChild(node);
}

function getHead(){
	return document.getElementsByTagName('head')[0];
}

function readCookie(name){
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for (i=0; i<ca.length; i++){
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ)==0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function createCookie(name,value,days){
	if (days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = '; expires='+date.toGMTString();
	}
	else expires = '';
	document.cookie = name+'='+value+expires+'; path=/';
}

function checkForUpdate(){
	if (readCookie(scriptName+'.checked')) return;
	GM_xmlhttpRequest({
		method: 'GET',
		url: 'http://polkila.googlecode.com/svn/trunk/'+scriptName+'.ver',
		onload: function(result){
			createCookie(scriptName+'.checked', true, 3);
			newVer = parseFloat(result.responseText);
			if (newVer>scriptVersion && confirm(lang?'There is a new version of '+scriptName+' script.\nDo You want to update?':'Появилась новая версия скрипта '+scriptName+'.\nОбновить?')){
				location.href = 'http://polkila.googlecode.com/files/'+scriptName+'.'+newVer+'.user.js';
			}
		}
	});
}
